//
//  RelevantRecommendationsView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/5.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit

class RelevantRecommendationsView: UIView, BottomShadow, AddCornerUIRectCorner, UITableViewDataSource, UITableViewDelegate {
    
    private let lMargin: CGFloat = 36
    private var rMargin: CGFloat = 0
    private let mainView = UIView()
    private let cellHeight: CGFloat = 65
    private let topViewHeight: CGFloat = 34
    private let maxCellCount: CGFloat = 5
    private var datas: [SearchRecommendModel] = []
    private var redatas: [GoodsModel] = []
    var type:Int?
    var commp: ((_ select: Int?) -> Void)? = nil
    func showData(datas: [SearchRecommendModel], rightMargin: CGFloat, complete: @escaping (_ selectIndex: Int?) -> Void) {
        self.datas = datas
        self.commp = complete
        rMargin = rightMargin
        let window = UIApplication.shared.keyWindow
        self.frame = window!.bounds
        self.alpha = 0.3
        self.backgroundColor = ONColor.maskBGColor
        window?.addSubview(self)
        UIView.animate(withDuration: TimeInterval(anTIME)) {
            self.alpha = 1
        }
        
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(hide))
        tap.cancelsTouchesInView = false
        self.addGestureRecognizer(tap)
        
        mainView.frame = CGRect(x: lMargin, y: 0, width: ScreenWidth - lMargin - rMargin, height: 0)
        mainView.backgroundColor = UIColor.white
        mainView.isUserInteractionEnabled = true
        self.addSubview(mainView)
        mainView.height = maxCellCount * cellHeight + topViewHeight
        mainView.centerY = self.height / 2
        
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        
        let topButton = UIButton(type: .custom)
        topButton.setTitle("相关推荐", for: .normal)
        topButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        topButton.backgroundColor = UIColor(hex: 0x01A1EB)
        topButton.isUserInteractionEnabled = false
        topButton.frame = CGRect(x: 0, y: 0, width: mainView.width, height: topViewHeight)
        mainView.addSubview(topButton)
        addCornerWithView(aView: topButton, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        let tableView = UITableView(frame: CGRect(x: 0, y: topButton.bottom, width: mainView.width, height: mainView.height - topButton.height - 5), style: .plain)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isUserInteractionEnabled = true
        tableView.showsVerticalScrollIndicator = false
        tableView.register(RelevantRecommendationsTableViewCell.self, forCellReuseIdentifier: "cell")
        mainView.addSubview(tableView)
        
    }
    
    func showData1(datas: [GoodsModel], rightMargin: CGFloat, complete: @escaping (_ selectIndex: Int?) -> Void) {
        self.type = 1
        self.redatas = datas
        self.commp = complete
        rMargin = rightMargin
        let window = UIApplication.shared.keyWindow
        self.frame = window!.bounds
        self.alpha = 0.3
        self.backgroundColor = ONColor.maskBGColor
        window?.addSubview(self)
        UIView.animate(withDuration: TimeInterval(anTIME)) {
            self.alpha = 1
        }
        
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(hide))
        tap.cancelsTouchesInView = false
        self.addGestureRecognizer(tap)
        
        mainView.frame = CGRect(x: lMargin, y: 0, width: ScreenWidth - lMargin - lMargin, height: 0)
        mainView.backgroundColor = UIColor.white
        mainView.isUserInteractionEnabled = true
        self.addSubview(mainView)
        mainView.height = maxCellCount * cellHeight + topViewHeight
        mainView.centerY = self.height / 2
        
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        
        let topButton = UIButton(type: .custom)
        topButton.setTitle("相关推荐", for: .normal)
        topButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        topButton.backgroundColor = UIColor(hex: 0x01A1EB)
        topButton.isUserInteractionEnabled = false
        topButton.frame = CGRect(x: 0, y: 0, width: mainView.width, height: topViewHeight)
        mainView.addSubview(topButton)
        addCornerWithView(aView: topButton, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        let tableView = UITableView(frame: CGRect(x: 0, y: topButton.bottom, width: mainView.width, height: mainView.height - topButton.height - 5), style: .plain)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isUserInteractionEnabled = true
        tableView.showsVerticalScrollIndicator = false
        tableView.register(RelevantRecommendationsTableViewCell.self, forCellReuseIdentifier: "cell")
        mainView.addSubview(tableView)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.type == 1 {
           return self.redatas.count
        }
        return self.datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? RelevantRecommendationsTableViewCell
        if self.type == 1 {
            cell?.setUIRe(model: redatas[indexPath.row])
        }else{
           cell?.setUI(model: datas[indexPath.row])
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.commp!(indexPath.row)
        hide()
    }
    
    @objc private func hide() {
        UIView.animate(withDuration: TimeInterval(anTIME), animations: {
            self.alpha = 0.3
        }) { (make) in
            self.removeFromSuperview()
        }
    }
}

class RelevantRecommendationsTableViewCell : UITableViewCell {
    private let showImageViewWithLeftMargin: CGFloat = 12
    private let rightMargin: CGFloat = 20
    private let titleLabelWithshowImageViewMargin: CGFloat = 15
    var showImageView = BaseCircleImageView()
    var titleLabel = UILabel()
    var contentLabel = UILabel()
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setUI(model:SearchRecommendModel) {
        self.selectionStyle = .none
        showImageView.contentMode = .scaleAspectFill
        showImageView.layer.cornerRadius = CORNERRADIUS
        showImageView.layer.masksToBounds = true
        self.addSubview(showImageView)
        showImageView.snp.makeConstraints { (make) in
            make.left.equalTo(self.snp.left).offset(showImageViewWithLeftMargin)
            make.centerY.equalTo(self.snp.centerY)
            make.size.equalTo(CGSize(width: 47, height: 47))
        }
        
        titleLabel.textColor = ONColor.subTextColor
        titleLabel.textAlignment = .left
        titleLabel.numberOfLines = 2
        titleLabel.lineBreakMode = .byWordWrapping
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints {[unowned self] (make) in
            make.left.equalTo(self.showImageView.snp.right).offset(titleLabelWithshowImageViewMargin)
            make.centerY.equalTo(self.snp.centerY)
            make.right.equalTo(self.snp.right).offset(-rightMargin)
        }
        
        contentLabel.textColor = ONColor.subTextColor
        contentLabel.font = UIFont.systemFont(ofSize: 14)
        self.addSubview(contentLabel)
        contentLabel.snp.makeConstraints {[unowned self] (make) in
            make.left.equalTo(self.showImageView.snp.right).offset(titleLabelWithshowImageViewMargin)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(5)
            make.right.equalTo(self.snp.right).offset(-rightMargin)
        }
        
        titleLabel.text = model.title!
//        contentLabel.text = "MB1开箱测评"
        contentLabel.isHidden = true
        if let image = model.image{
            let path:String = "\(BaseURL)\(image)"
            let url = NSURL.init(string: path)
            showImageView.sd_setImage(with: url! as URL, completed: nil)
        }
        
        

//        showImageView.image = UIImage(named: "comment_img4.JPG")
    }
    
    
    func setUIRe(model:GoodsModel) {
        self.selectionStyle = .none
        showImageView.contentMode = .scaleAspectFill
        showImageView.layer.cornerRadius = CORNERRADIUS
        showImageView.layer.masksToBounds = true
        self.addSubview(showImageView)
        showImageView.snp.makeConstraints { (make) in
            make.left.equalTo(self.snp.left).offset(showImageViewWithLeftMargin)
            make.centerY.equalTo(self.snp.centerY)
            make.size.equalTo(CGSize(width: 47, height: 47))
        }
        
        titleLabel.textColor = ONColor.subTextColor
        titleLabel.textAlignment = .left
        titleLabel.numberOfLines = 2
        titleLabel.lineBreakMode = .byWordWrapping
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints {[unowned self] (make) in
            make.left.equalTo(self.showImageView.snp.right).offset(titleLabelWithshowImageViewMargin)
            make.centerY.equalTo(self.snp.centerY).offset(-10)
            make.right.equalTo(self.snp.right).offset(-rightMargin)
        }
        
        contentLabel.textColor = ONColor.subTextColor
        contentLabel.font = UIFont.systemFont(ofSize: 14)
        self.addSubview(contentLabel)
        contentLabel.snp.makeConstraints {[unowned self] (make) in
            make.left.equalTo(self.showImageView.snp.right).offset(titleLabelWithshowImageViewMargin)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(5)
            make.right.equalTo(self.snp.right).offset(-rightMargin)
        }
        
        titleLabel.text = model.goodsName!
        //        contentLabel.text = "MB1开箱测评"
        contentLabel.text = "¥"+model.specifications![0].price!
        if let image = model.coverPath{
            showImageView.sd_setImage(with: appendUrl(suffix: image), completed: nil)
        }
        
        
        
        //        showImageView.image = UIImage(named: "comment_img4.JPG")
    }
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view?.superview is RelevantRecommendationsTableViewCell{
            
            return false
        }
        return true
    }
}
